package net.huashitong.service.user;

import net.huashitong.mapper.user.SsUserValidMapper;
import net.huashitong.ssydt.user.entity.SsUserValid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author shaoxian.zhong
 * @create 2018-06-25 17:58
 */
@Service
@Transactional
public class SsWebUserValidServiceImpl implements SsUserValidService {

    private SsUserValidMapper mapper;

    @Autowired
    public SsWebUserValidServiceImpl(SsUserValidMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public SsUserValid getByMobileOnLastTime(String mobile) {
        return mapper.getByMobileOnLastTime(mobile);
    }

    @Override
    public void save(SsUserValid ssUserValid) {
        mapper.save(ssUserValid);
    }

    @Override
    public void updateByIdOnIsEnabled(SsUserValid ssUserValid) {
        mapper.updateByIdOnIsEnabled(ssUserValid);
    }

    @Override
    public boolean isPast5MinOrErr(String mobile, String code) {
        SsUserValid ssUserValid = getByMobileOnLastTime(mobile);

        //用户攻击
        if (ssUserValid == null) {
            return true;
        }

        //验证码已经使用
        if (ssUserValid.getIsEnabled() == 1) {
            return true;
        }

        //判断验证码是否正确
        if (!ssUserValid.getVaildCode().equals(code)) {
            return true;
        }

        //判断验证码是否超时
        long timeSpace = getTimeSpace(ssUserValid.getSendCurrentTimeMillis());
        if (timeSpace > 5) {
            return true;
        }

        //状态更新为已读，下次不走验证，需要重新发验证码
        ssUserValid.setIsEnabled(1);
        updateByIdOnIsEnabled(ssUserValid);
        return false;
    }

    /**
     * 获取时间戳间隔
     *
     * @param oldTimeMillis 减去的时间
     * @return 相差的分钟数
     */
    private long getTimeSpace(Long oldTimeMillis) {
        return (System.currentTimeMillis() - oldTimeMillis) / (1000 * 60);
    }
}
